<?php
declare(strict_types=1);

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;

/**
 * 销售模块控制器
 */
class Sales extends BaseController
{
    /**
     * 获取销售订单列表
     */
    public function getOrderList()
    {
        $page = Request::param('page', 1);
        $limit = Request::param('limit', 10);
        $search = Request::param('search', '');
        $status = Request::param('status', '');
        $customer_id = Request::param('customer_id', '');
        
        $where = [];
        if (!empty($search)) {
            $where[] = ['order_no|customer_id', 'like', "%{$search}%"];
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        if ($customer_id !== '') {
            $where[] = ['customer_id', '=', $customer_id];
        }
        
        $count = Db::name('sales_order')->where($where)->count();
        $list = Db::name('sales_order')
            ->where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        // 关联客户和销售员信息
        foreach ($list as &$item) {
            $customer = Db::name('customer')->where('id', $item['customer_id'])->find();
            $salesperson = Db::name('user')->where('id', $item['salesperson_id'])->find();
            $item['customer_name'] = $customer ? $customer['customer_name'] : '';
            $item['salesperson_name'] = $salesperson ? $salesperson['realname'] : '';
        }
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
    }
    
    /**
     * 添加销售订单
     */
    public function addOrder()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'customer_id' => 'require|number',
            'order_date' => 'require|date',
            'delivery_date' => 'require|date',
            'total_amount' => 'require|float',
            'salesperson_id' => 'require|number',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 生成销售订单号
        $data['order_no'] = 'XS' . date('YmdHis') . rand(1000, 9999);
        $data['create_time'] = date('Y-m-d H:i:s');
        
        Db::startTrans();
        try {
            // 保存销售订单主表
            $orderId = Db::name('sales_order')->insertGetId($data);
            
            // 保存销售订单明细
            if (!empty($data['details']) && is_array($data['details'])) {
                foreach ($data['details'] as $detail) {
                    $detail['order_id'] = $orderId;
                    $detail['create_time'] = date('Y-m-d H:i:s');
                    Db::name('sales_order_detail')->insert($detail);
                }
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '添加成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'msg' => '添加失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 更新销售订单
     */
    public function updateOrder()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'customer_id' => 'require|number',
            'order_date' => 'require|date',
            'delivery_date' => 'require|date',
            'total_amount' => 'require|float',
            'salesperson_id' => 'require|number',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        $data['update_time'] = date('Y-m-d H:i:s');
        
        Db::startTrans();
        try {
            // 更新销售订单主表
            Db::name('sales_order')->update($data);
            
            // 如果有明细数据，先删除原有明细，再添加新明细
            if (!empty($data['details']) && is_array($data['details'])) {
                // 删除原有明细
                Db::name('sales_order_detail')->where('order_id', $data['id'])->delete();
                
                // 添加新明细
                foreach ($data['details'] as $detail) {
                    $detail['order_id'] = $data['id'];
                    $detail['create_time'] = date('Y-m-d H:i:s');
                    Db::name('sales_order_detail')->insert($detail);
                }
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'msg' => '更新失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除销售订单
     */
    public function deleteOrder()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 检查是否有关联的发货单
        $hasDelivery = Db::name('sales_delivery')
            ->where('order_id', $id)
            ->find();
            
        if ($hasDelivery) {
            return json(['code' => 400, 'msg' => '该订单有关联的发货单，无法删除']);
        }
        
        // 检查是否有关联的退货单
        $hasReturn = Db::name('sales_return')
            ->where('order_id', $id)
            ->find();
            
        if ($hasReturn) {
            return json(['code' => 400, 'msg' => '该订单有关联的退货单，无法删除']);
        }
        
        Db::startTrans();
        try {
            // 删除订单明细
            Db::name('sales_order_detail')->where('order_id', $id)->delete();
            
            // 删除订单主表
            Db::name('sales_order')->delete($id);
            
            Db::commit();
            return json(['code' => 200, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取销售订单详情
     */
    public function getOrderDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 获取订单主表信息
        $order = Db::name('sales_order')->where('id', $id)->find();
        
        if (!$order) {
            return json(['code' => 400, 'msg' => '订单不存在']);
        }
        
        // 关联客户和销售员信息
        $customer = Db::name('customer')->where('id', $order['customer_id'])->find();
        $salesperson = Db::name('user')->where('id', $order['salesperson_id'])->find();
        $order['customer_name'] = $customer ? $customer['customer_name'] : '';
        $order['salesperson_name'] = $salesperson ? $salesperson['realname'] : '';
        
        // 获取订单明细
        $details = Db::name('sales_order_detail')
            ->where('order_id', $id)
            ->select()
            ->toArray();
            
        // 关联产品信息
        foreach ($details as &$detail) {
            $product = Db::name('product')->where('id', $detail['product_id'])->find();
            $detail['product_name'] = $product ? $product['product_name'] : '';
            $detail['product_code'] = $product ? $product['product_code'] : '';
        }
        
        $order['details'] = $details;
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $order]);
    }
    
    /**
     * 获取销售发货单列表
     */
    public function getDeliveryList()
    {
        $page = Request::param('page', 1);
        $limit = Request::param('limit', 10);
        $search = Request::param('search', '');
        $status = Request::param('status', '');
        $order_id = Request::param('order_id', '');
        
        $where = [];
        if (!empty($search)) {
            $where[] = ['delivery_no', 'like', "%{$search}%"];
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        if ($order_id !== '') {
            $where[] = ['order_id', '=', $order_id];
        }
        
        $count = Db::name('sales_delivery')->where($where)->count();
        $list = Db::name('sales_delivery')
            ->where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        // 关联订单和操作员信息
        foreach ($list as &$item) {
            $order = Db::name('sales_order')->where('id', $item['order_id'])->find();
            $operator = Db::name('user')->where('id', $item['operator_id'])->find();
            $item['order_no'] = $order ? $order['order_no'] : '';
            $item['operator_name'] = $operator ? $operator['realname'] : '';
            
            if ($order) {
                $customer = Db::name('customer')->where('id', $order['customer_id'])->find();
                $item['customer_name'] = $customer ? $customer['customer_name'] : '';
            } else {
                $item['customer_name'] = '';
            }
        }
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
    }
    
    /**
     * 添加销售发货单
     */
    public function addDelivery()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'order_id' => 'require|number',
            'delivery_date' => 'require|date',
            'operator_id' => 'require|number',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 生成发货单号
        $data['delivery_no'] = 'FH' . date('YmdHis') . rand(1000, 9999);
        $data['create_time'] = date('Y-m-d H:i:s');
        $result = Db::name('sales_delivery')->insert($data);
        
        if ($result) {
            // 如果状态为已发货，更新订单状态
            if ($data['status'] == 2) {
                Db::name('sales_order')
                    ->where('id', $data['order_id'])
                    ->update([
                        'status' => 2, // 处理中
                        'update_time' => date('Y-m-d H:i:s')
                    ]);
            }
            
            return json(['code' => 200, 'msg' => '添加成功']);
        } else {
            return json(['code' => 400, 'msg' => '添加失败']);
        }
    }
    
    /**
     * 更新销售发货单
     */
    public function updateDelivery()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'order_id' => 'require|number',
            'delivery_date' => 'require|date',
            'operator_id' => 'require|number',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        $data['update_time'] = date('Y-m-d H:i:s');
        
        Db::startTrans();
        try {
            // 获取原发货单信息
            $oldDelivery = Db::name('sales_delivery')->where('id', $data['id'])->find();
            $oldStatus = $oldDelivery['status'];
            
            // 更新发货单
            $result = Db::name('sales_delivery')->update($data);
            
            // 如果状态从未发货变为已发货，更新订单状态
            if ($oldStatus != 2 && $data['status'] == 2) {
                Db::name('sales_order')
                    ->where('id', $data['order_id'])
                    ->update([
                        'status' => 2, // 处理中
                        'update_time' => date('Y-m-d H:i:s')
                    ]);
            }
            
            // 如果状态从未签收变为已签收，更新订单状态
            if ($oldStatus != 3 && $data['status'] == 3) {
                Db::name('sales_order')
                    ->where('id', $data['order_id'])
                    ->update([
                        'status' => 3, // 已完成
                        'update_time' => date('Y-m-d H:i:s')
                    ]);
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'msg' => '更新失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除销售发货单
     */
    public function deleteDelivery()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $result = Db::name('sales_delivery')->delete($id);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 获取销售退货单列表
     */
    public function getReturnList()
    {
        $page = Request::param('page', 1);
        $limit = Request::param('limit', 10);
        $search = Request::param('search', '');
        $status = Request::param('status', '');
        $order_id = Request::param('order_id', '');
        
        $where = [];
        if (!empty($search)) {
            $where[] = ['return_no', 'like', "%{$search}%"];
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        if ($order_id !== '') {
            $where[] = ['order_id', '=', $order_id];
        }
        
        $count = Db::name('sales_return')->where($where)->count();
        $list = Db::name('sales_return')
            ->where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        // 关联订单和操作员信息
        foreach ($list as &$item) {
            $order = Db::name('sales_order')->where('id', $item['order_id'])->find();
            $operator = Db::name('user')->where('id', $item['operator_id'])->find();
            $item['order_no'] = $order ? $order['order_no'] : '';
            $item['operator_name'] = $operator ? $operator['realname'] : '';
            
            if ($order) {
                $customer = Db::name('customer')->where('id', $order['customer_id'])->find();
                $item['customer_name'] = $customer ? $customer['customer_name'] : '';
            } else {
                $item['customer_name'] = '';
            }
        }
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
    }
    
    /**
     * 添加销售退货单
     */
    public function addReturn()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'order_id' => 'require|number',
            'return_date' => 'require|date',
            'reason' => 'require',
            'operator_id' => 'require|number',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 生成退货单号
        $data['return_no'] = 'TH' . date('YmdHis') . rand(1000, 9999);
        $data['create_time'] = date('Y-m-d H:i:s');
        $result = Db::name('sales_return')->insert($data);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '添加成功']);
        } else {
            return json(['code' => 400, 'msg' => '添加失败']);
        }
    }
    
    /**
     * 更新销售退货单
     */
    public function updateReturn()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'order_id' => 'require|number',
            'return_date' => 'require|date',
            'reason' => 'require',
            'operator_id' => 'require|number',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        $data['update_time'] = date('Y-m-d H:i:s');
        $result = Db::name('sales_return')->update($data);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '更新成功']);
        } else {
            return json(['code' => 400, 'msg' => '更新失败']);
        }
    }
    
    /**
     * 删除销售退货单
     */
    public function deleteReturn()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $result = Db::name('sales_return')->delete($id);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 获取销售统计数据
     */
    public function getSalesStatistics()
    {
        // 获取当月销售订单数
        $monthStart = date('Y-m-01');
        $monthEnd = date('Y-m-t');
        $monthOrderCount = Db::name('sales_order')
            ->where('order_date', '>=', $monthStart)
            ->where('order_date', '<=', $monthEnd)
            ->count();
            
        // 获取当月销售总额
        $monthSalesAmount = Db::name('sales_order')
            ->where('order_date', '>=', $monthStart)
            ->where('order_date', '<=', $monthEnd)
            ->sum('total_amount');
            
        // 获取销售员业绩排行
        $salesPersonRanking = Db::name('sales_order')
            ->field('salesperson_id, SUM(total_amount) as total_sales')
            ->where('order_date', '>=', $monthStart)
            ->where('order_date', '<=', $monthEnd)
            ->group('salesperson_id')
            ->order('total_sales', 'desc')
            ->limit(5)
            ->select()
            ->toArray();
            
        // 关联销售员信息
        foreach ($salesPersonRanking as &$item) {
            $salesperson = Db::name('user')->where('id', $item['salesperson_id'])->find();
            $item['salesperson_name'] = $salesperson ? $salesperson['realname'] : '';
        }
        
        // 获取产品销售排行
        $productRanking = Db::name('sales_order_detail')
            ->alias('d')
            ->join('sales_order o', 'd.order_id = o.id')
            ->field('d.product_id, SUM(d.quantity) as total_quantity, SUM(d.amount) as total_amount')
            ->where('o.order_date', '>=', $monthStart)
            ->where('o.order_date', '<=', $monthEnd)
            ->group('d.product_id')
            ->order('total_amount', 'desc')
            ->limit(5)
            ->select()
            ->toArray();
            
        // 关联产品信息
        foreach ($productRanking as &$item) {
            $product = Db::name('product')->where('id', $item['product_id'])->find();
            $item['product_name'] = $product ? $product['product_name'] : '';
        }
        
        return json([
            'code' => 200, 
            'msg' => '获取成功', 
            'data' => [
                'month_order_count' => $monthOrderCount,
                'month_sales_amount' => $monthSalesAmount,
                'salesperson_ranking' => $salesPersonRanking,
                'product_ranking' => $productRanking
            ]
        ]);
    }
}
